package com.book.service.impl;

import com.book.dao.AdminMapper;
import com.book.entity.Admin;
import com.book.service.AdminService;
import com.book.utils.MyBatisUtil;
import jakarta.servlet.http.HttpSession;
import lombok.extern.java.Log;
import org.apache.ibatis.session.SqlSession;

import java.util.Objects;

/**
 * @Author zzw2000
 * @Date 2022年08月10日 20:37
 * @Description 描述
 */
@Log
public class AdminServiceImpl implements AdminService {
    @Override
    public boolean auth(String username, String password, HttpSession session) {

        try (SqlSession sqlSession = MyBatisUtil.getSqlSession(true)) {
            AdminMapper mapper = sqlSession.getMapper(AdminMapper.class);
            Admin admin = mapper.getAdmin(username, password);
            if (Objects.isNull(admin)) {
                log.info("用户登录验证失败，用户名或密码错误！");
                return false;
            }
            log.info("用户登录验证：" + admin);
            session.setAttribute("user", admin);
            return true;
        }
    }

    @Override
    public boolean register(String username, String nickname, String password) {
        try (SqlSession sqlSession = MyBatisUtil.getSqlSession(true)) {
            AdminMapper mapper = sqlSession.getMapper(AdminMapper.class);
            if (Objects.nonNull(mapper.getOne(username))) {
                return false;
            }
            int flag = mapper.register(username, nickname, password);
            return flag > 0;
        }
    }

    @Override
    public boolean updateInfo(int id, String nickname, String password) {
        try (SqlSession sqlSession = MyBatisUtil.getSqlSession(true)) {
            AdminMapper mapper = sqlSession.getMapper(AdminMapper.class);
            int flag = mapper.updateInfo(id, nickname, password);
            return flag > 0;
        }
    }
}
